package com.hanserwei.community.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanserwei.community.entity.common.ApiResponse;
import com.hanserwei.community.entity.po.User;
import com.hanserwei.community.entity.request.user.*;
import com.hanserwei.community.entity.vo.UserVO;
import com.hanserwei.community.exception.ApiException;
import com.hanserwei.community.manager.RedisManager;
import com.hanserwei.community.service.UserService;
import com.hanserwei.community.uitils.JWTUtils;
import com.hanserwei.community.uitils.ThrowUtils;
import com.hanserwei.community.enums.ResponseCodeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    private final RedisManager redisManager;

    @GetMapping("/createCaptcha")
    @Operation(summary = "创建验证码")
    public ApiResponse<Map<String, String>> createCaptcha(@RequestParam String captchaId) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 45, 4, 10);
        String idStr = captchaId;
        if (StrUtil.isEmpty(captchaId)) {
            idStr = IdUtil.getSnowflakeNextIdStr();
        }
        String code = lineCaptcha.getCode();
        redisManager.setCaptcha(idStr, code);
        Map<String, String> map = Map.of(
                "captchaId", idStr,
                "imgBase64", lineCaptcha.getImageBase64Data()
        );
        return ApiResponse.success(map);
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public ApiResponse<UserVO> userLogin(@RequestBody UserLoginRequest request) {
        String captcha = redisManager.getCaptcha(request.getCaptchaId());
        if (!captcha.equalsIgnoreCase(request.getCaptcha())) {
            throw new ApiException(ResponseCodeEnum.USER_CAPTCHA_ERROR, "验证码错误");
        }
        UserVO userVO = userService.userLogin(request);
        if (userVO != null) {
            Integer id = userVO.getId();
            String username = userVO.getUserName();
            Integer userType = userVO.getType();
            // 3. 准备生成 JWT Token 的 claims
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", id);
            claims.put("userName", username);
            claims.put("userType", userType);
            // 4. 调用 JWTUtils 生成 Token
            String token = JWTUtils.generateToken(claims);
            userVO.setToken(token);
            System.out.println(token);
        }
        return ApiResponse.success("登录成功！", userVO);
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public ApiResponse<UserVO> userRegister(@RequestBody UserRegisterRequest request) {
        String captcha = redisManager.getCaptcha(request.getCaptchaId());
        if (!captcha.equalsIgnoreCase(request.getCaptcha())) {
            throw new ApiException(ResponseCodeEnum.USER_CAPTCHA_ERROR, "验证码错误");
        }
        UserVO userVO = userService.userRegister(request);
        return ApiResponse.success("注册成功！", userVO);
    }

    @PostMapping("/list")
    @Operation(summary = "查询用户列表")
    public ApiResponse<Page<User>> queryUserByPage(@RequestBody UserQueryRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        Page<User> result = userService.queryUserByPage(request);
        ThrowUtils.throwIf(result == null, ResponseCodeEnum.USER_NOT_FOUND, "查询失败！");
        return ApiResponse.success("查询成功！", result);
    }

    @PostMapping("/add")
    @Operation(summary = "添加用户")
    public ApiResponse<User> addUser(@RequestBody UserAddRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User result = userService.addUser(request);
        ThrowUtils.throwIf(result == null, ResponseCodeEnum.USER_NOT_FOUND, "添加失败！");
        return ApiResponse.success("添加成功！", result);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户")
    public ApiResponse<String> deleteUser(@Parameter(description = "用户ID") @RequestParam Integer id) {
        ThrowUtils.throwIf(id == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        boolean result = userService.removeById(id);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.USER_NOT_FOUND, "删除失败！");
        return ApiResponse.success("删除成功！");
    }

    @PutMapping("/update/{id}")
    @Operation(summary = "更新用户")
    public ApiResponse<Boolean> updateUser(@ModelAttribute UserUpdateRequest request,
                                           @Parameter(description = "用户ID")
                                           @PathVariable Integer id) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        boolean result = userService.updateUser(request, id);
        return ApiResponse.success("更新成功！", result);
    }

    @DeleteMapping("/deleteBatch")
    @Operation(summary = "批量删除用户")
    public ApiResponse<Boolean> deleteUserBatch(@Parameter(description = "用户ID列表") @RequestBody Integer[] ids) {
        ThrowUtils.throwIf(ids == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        boolean result = userService.removeByIds(List.of(ids));
        ThrowUtils.throwIf(!result, ResponseCodeEnum.USER_NOT_FOUND, "删除失败！");
        return ApiResponse.success("删除成功！", true);
    }

}
